import {refreshToken} from "../utils/jwt";

export function auth(must: boolean) {
    return function (ctx, next) {
        const token = ctx.request.headers.token
        if (must && !token) {
            ctx.response.status = 401
            ctx.response.message = "无效Token!"
            return
        }
        if (!token) {
            next()
            return
        }
        const newInf = refreshToken(token)
        if (newInf.err) {
            ctx.response.status = 401
            ctx.response.message = newInf.err
            return
        }
        if (!ctx.Map) ctx.Map = {}
        ctx.Map.uid = newInf.uid
        next()
    }
}